package com.egreen.pointsmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.egreen.common.States;
import com.egreen.common.pojo.DTO.pointsmall.CartUpdateDTO;
import com.egreen.common.pojo.DTO.pointsmall.commitOrderDTO;
import com.egreen.common.pojo.VO.pointsmall.CartVO;
import com.egreen.common.pojo.entity.order.OrderDetail;
import com.egreen.common.pojo.entity.pointsmall.*;
import com.egreen.pointsmall.dao.*;
import com.egreen.pointsmall.exception.PointsmallException;
import com.egreen.pointsmall.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egreen.pointsmall.utils.seriaNumberMake;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author yyf
 * @since 2023-04-05
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartDao, Cart> implements ICartService {
    @Autowired
    private CartDao cartDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private OrdersDetailDao ordersDetailsDao;
    @Autowired
    private UserAddressDao userAddressDao;

    @Override
    @Transactional //添加事务保证
    public boolean add(Cart cart) {
        //添加购物车操作
        int insert = cartDao.insert(cart);
        if (insert != 1) {
            throw new PointsmallException(States.CART_ADD_ERROR);
        }
        Product product = productDao.selectById(cart.getProductId());
        if (product == null) {
            //表示没有当前商品
            throw new PointsmallException(States.PRODUCT_NOT_EXISTS);
        }
        if (product.getStock() == 0) {
            throw new PointsmallException(States.PRODUCT_STOCK_ERROR);
        }
        Integer stock = product.getStock() - cart.getQuantity();
        if (stock < 0) {
            throw new PointsmallException(States.PRODUCT_STOCK_ERROR);
        }
        //进行商品减库存操作
        Product productnew = new Product();
        productnew.setStock(stock);
        productnew.setId(cart.getProductId());
        productDao.updateById(productnew);
        return true;
    }

    @Override
    public List<CartVO> getCartVoList(Integer userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Cart> carts = cartDao.selectList(queryWrapper);
        List<CartVO> cartVOS = new ArrayList<>();
        for (Cart cart : carts) {
            CartVO cartVO = new CartVO();
            Product product = productDao.selectById(cart.getProductId());
            BeanUtils.copyProperties(product, cartVO);
            BeanUtils.copyProperties(cart, cartVO);
            cartVOS.add(cartVO);
        }
        return cartVOS;
    }

    @Override
    @Transactional
    public boolean updateCart(CartUpdateDTO cartUpdateDTO) {
        //先进行判断，当前是加操作还是减操作
        Cart oldcart = cartDao.selectById(cartUpdateDTO.getId());
        Product product = productDao.selectById(oldcart.getProductId());
        Product productnew = new Product();
        Integer quantitynew;
        if (oldcart.getQuantity() < cartUpdateDTO.getQuantity()) {
            //表示当前是一个购物车的加操作
            quantitynew = cartUpdateDTO.getQuantity() - oldcart.getQuantity();
            productnew.setStock(product.getStock() - quantitynew);
        } else if (oldcart.getQuantity() > cartUpdateDTO.getQuantity()) {
            //表示这是一个减操作
            quantitynew = oldcart.getQuantity() - cartUpdateDTO.getQuantity();
            productnew.setStock(product.getStock() + quantitynew);
        } else {
            throw new PointsmallException(States.CART_UPDATE_PARAMETER_ERROR);
        }
        productnew.setId(oldcart.getProductId());
        int updateStock = productDao.updateById(productnew);
        if (updateStock != 1) {
            throw new PointsmallException(States.CART_UPDATE_ERROR);
        }
        //更新数量和费用和库存
        Cart cart = new Cart();
        BeanUtils.copyProperties(cartUpdateDTO, cart);
        int i = cartDao.updateById(cart);
        if (i != 1) {
            throw new PointsmallException(States.ERR_UPDATE);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean delete(Integer id) {
        //先进行商品库存的修改
        Cart cart = cartDao.selectById(id);
        Product product = productDao.selectById(cart.getProductId());
        Integer newStock=cart.getQuantity()+product.getStock();
        Product newproduct=new Product();
        newproduct.setStock(newStock);
        newproduct.setId(cart.getProductId());
        int updateStock = productDao.updateById(newproduct);
        if (updateStock!=1){
            throw new PointsmallException(States.CART_UPDATE_STOCK_ERROR);
        }
        //再进行购物车的删除
        int delete = cartDao.deleteById(id);
        if (delete!=1){
            throw new PointsmallException(States.CART_REMOVE_ERROR);
        }
        return true;
    }

    @Override
    @Transactional
    public Orders commit(commitOrderDTO commitOrderDTO, PointsUser user) {
        //处理地址
        if (!commitOrderDTO.getUserAddress().equals("newAddress")){
            commitOrderDTO.setAddress(commitOrderDTO.getUserAddress());
        }else {
            //新地址存入数据库
        UserAddress userAddress=new UserAddress();
        userAddress.setAddress(commitOrderDTO.getAddress());
        userAddress.setIsdefault(0);
        userAddress.setUserId(user.getId());
        userAddress.setRemark(commitOrderDTO.getRemark());
            int insert = userAddressDao.insert(userAddress);
            if (insert==0){
                throw new PointsmallException(States.USER_ADDRESS_ADD_ERROR);
            }
        }
        //创建订单表
        Orders orders=new Orders();
        orders.setUserId(user.getId());
        orders.setLoginName(user.getLoginName());
        orders.setUserAddress(commitOrderDTO.getAddress());
        QueryWrapper<Cart>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getId());
        List<Cart> carts = cartDao.selectList(queryWrapper);
        Float cost=0f;
        for (Cart cart : carts) {
            cost=cost+cart.getCost();
        }
        orders.setPointcost(cost);
        String seriaNumber = seriaNumberMake.seriaNumberMake();
        orders.setSerialnumber(seriaNumber);
        int insert = ordersDao.insert(orders);
        if (insert!=1){
            throw new PointsmallException(States.ORDERS_CREATE_ERROR);
        }
        //创建订单详情表
        for (Cart cart : carts) {
            OrdersDetail ordersDetail=new OrdersDetail();
            BeanUtils.copyProperties(cart,ordersDetail);
            ordersDetail.setOrderId(orders.getId());
            ordersDetail.setPointcost(cost);
            int insertOrderDetail= ordersDetailsDao.insert(ordersDetail);
            if (insertOrderDetail==0){
                throw new PointsmallException(States.ORDER_DETAIL_CREATE_ERROR);
            }
        }
        //清空当前购物车
        int delete = cartDao.delete(queryWrapper);
        if (delete==0){
            throw new PointsmallException(States.CART_REMOVE_ERROR);
        }
        return orders;
    }
}
